package me.ctidy.assignment04.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import lombok.AllArgsConstructor;
import me.ctidy.assignment04.R;
import me.ctidy.assignment04.entity.Assets;

import java.util.List;

/**
 * AssetsAdapter
 *
 * @author ctidy
 */
@AllArgsConstructor
public class AssetsAdapter extends BaseAdapter {

    private final Context context;
    private final List<Assets> data;

    /**
     * @return 展示行数
     */
    @Override
    public int getCount() {
        return data.size();
    }

    /**
     * @param position 位置索引
     * @return 指定位置的用户数据
     */
    @Override
    public Assets getItem(int position) {
        return data.get(position);
    }

    /**
     * @param position 位置索引
     * @return assets id
     */
    @Override
    public long getItemId(int position) {
        return getItem(position).getId();
    }

    /**
     * 获取目标渲染 View
     *
     * @param position    位置索引
     * @param convertView 展示数据的目标 View
     * @param parent      父组件
     * @return 展示数据的目标 View
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // I. 缓存
        ViewHolder holder;
        if (convertView == null) {
            // 初始化, 之前从未创建过 View
            // 将布局转换成 View 对象
            convertView = LayoutInflater.from(context)
                    .inflate(R.layout.item_info, null);
            // 创建数据缓存, 现在 View 的 tag 中占位 (引用数据类型) , 方法最后进行赋值
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            // 之前创建过 View, 从 tag 中重新获取缓存对象, 方法最后更新数据
            holder = (ViewHolder) convertView.getTag();
        }

        // II. 获取数据
        final Assets assets = getItem(position);
        int iconId = assets.getAssetsType().getIconId();

        // III. 准备展示内容
        holder.ivHeadIcon.setImageResource(iconId);
        holder.tvTitleAbove.setText(convertView.getResources().getString(assets.getAssetsType().getLocalName()) + " : " + assets.getAssetsName());
        holder.tvTitleCentral.setText(String.valueOf(assets.getAssetsMoney()));
        holder.tvDesc.setText(assets.getRemarks());

        return convertView;
    }

    /**
     * 静态内部类, 用于缓存视图数据
     */
    private static class ViewHolder {
        ImageView ivHeadIcon;
        TextView tvTitleAbove, tvTitleCentral, tvDesc, tvTime;

        public ViewHolder(View view) {
            ivHeadIcon = view.findViewById(R.id.ii_iv_head);
            tvTitleAbove = view.findViewById(R.id.ii_tv_title_above);
            tvTitleCentral = view.findViewById(R.id.ii_tv_title_central);
            tvDesc = view.findViewById(R.id.ii_tv_desc);
            tvTime = view.findViewById(R.id.ii_tv_time);
            tvTime.setVisibility(View.GONE);  // 隐藏 time 组件
        }
    }
}
